// pages/yingyuan/detail.js
var timetool = require('../../utils/time.js');
var req = require('../../interfaceImpl.js');
var config = require('../../interfaceConfig.js');
var pojo = ''
var reqfilmSign = '';
var cinemapojo = ''
var strAppCode = "2018SmallApp"
var imgpath = config.imgHost;
var filmCode = ''
var movielist = [];
var isSelected = "";
var idx = 0;
var filePlanSgin = "";  //
var reqfilePlanSgin = ""; //获取电影日期签名
var reqplanSgin = "";  //获取电影排期签名
var startdate = "";
var enddate = "";
var showdate = [];
var plandate = []; //电影拍档
var curplandate = ''
var app = getApp();
var code = "";
var showandpaymoney =
  Page({

    /**
     * 页面的初始数据
     */
    data: {
      scrollx:true,
      indexnum: 0,
      chkid: 0,
      current: 0,
      chkmovieimg: '',//电影的图片
      dyid: 0,//电影id，
      dyname: '',//电影的名称

      yyid: 0,//影院id
      yyname: '',//影院name
      address: '',//影院地址
      minprice: '30.0',//影院最低价
      movielist: [],//电影列表
      changcilist: [],//场次
      imgpath: imgpath,
      istoday: true,//默认今天
      isnextday: false,//明天
      islastday: false,//后天
      today: '',//今天的日期
      nextday: '',//明天的日期
      lastday: '',//后天的日期
      moreday: '',
      moreqday: '',
      morewday: '',
      moreeday: '',
      chkday: '',//选中的日期

      iswuchangci: false,//是否没有场次

      setWidth: '100%',
      isSelected: 0,
      isCurrent: 0,
      translateX: "50%"
    },
    /**购票**/
    gobuypiao: function (e) {
        wx.showLoading({
           mask: true
        })
      var that = this;
      curplandate = e.currentTarget.dataset.pojo;//场次id

      var chkday = that.data.chkday;//选中的日期
      if (app.globalData.hasLogin) { //TODO记得修改
        console.log(1212121)
        //TODO DO NOTHING
        wx.navigateTo({
          url: '../yingting/index?Cinemapojo=' + JSON.stringify(cinemapojo) + '&&plandate=' + JSON.stringify(curplandate) + '&&showdate=' + showdate[idx] + ''
        })
      } else {
        wx.login({
          success: function (res) {
            console.log(res)
            code = res.code;
            return req.MiniAppLogin(code).then(res => {
              if (res.data.notRegister) {//TODO记得修改
                wx.reLaunch({
                  url: '../regiest/regiest?Cinemapojo=' + JSON.stringify(cinemapojo) + '&&plandate=' + JSON.stringify(curplandate) + '&&showdate=' + showdate[idx] + '&&frombuy=true'
                })
              } else {
                var token = res.data.data
                //TODO请求用户信息
                app.globalData.hasLogin = true;
                app.globalData.token = token;
                return req.GetUserInfo(token).then(res => {
                  if (res.data.success) {
                    app.globalData.loginuserinfo = res.data.data // res.data.data
                    that.setData({ phone: app.globalData.loginuserinfo.mobile, hasLogin: true })
                    console.log(app.globalData.loginuserinfo)
                    that.setData({ hasF: true })
                    wx.getUserInfo({
                      success: function (res) {
                        app.globalData.userinfo = res.userInfo
                        console.log(res)
                        that.setData({ userinfo: app.globalData.userinfo })
                        wx.navigateTo({
                          url: '../yingting/index?Cinemapojo=' + JSON.stringify(cinemapojo) + '&&plandate=' + JSON.stringify(curplandate) + '&&showdate=' + showdate[idx] + ''
                        })
                      }, fail: function () {
                        //拒绝授权
                        wx.navigateTo({
                          url: '../yingting/index?Cinemapojo=' + JSON.stringify(cinemapojo) + '&&plandate=' + JSON.stringify(curplandate) + '&&showdate=' + showdate[idx] + ''
                        })
                      },

                    })

                  } else {
                    wx.showModal({
                      title: '提示',
                      content: '登陆失败,请检查网络',
                    })
                    return 
                  }
                })
              }
            })
          }, fail: function (res) {
            wx.showModal({
              title: '提示',
              content: '登陆失败',
            })
            return 
          }
        })

      }

      //结束标识符
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      wx.showLoading({mask: true});
      var that = this;
      pojo = JSON.parse(options.pojo)
      cinemapojo = JSON.parse(options.cinemapojo)
      filmCode = pojo.FilmCode;
      console.log(filmCode)
      console.log(cinemapojo)
      //设置页头
      wx.setNavigationBarTitle({
        title: cinemapojo.CinemaName,
      })
      //页面参数值
      that.setData({
        pojo,
        cinemapojo
      })
      var curdate = pojo.SyncTime.split("T")[0]
      var Filmssign = "strAppCode=" + strAppCode + '&CinemaCode=' + cinemapojo.CinemaCode + '&PlayDate=' + curdate;

      filePlanSgin = "strAppCode=" + strAppCode + "CinemaCode=" + cinemapojo.CinemaCode + "FilmCode=" + filmCode + "PlayStartDate=" + "PlayEndDate=";

      return req.GetSignStr(Filmssign).then(res => {
        if (res.data.success)
          reqfilmSign = res.data.data;

      }).then(() => {
        return req.GetFilmLis(strAppCode, cinemapojo.CinemaCode, curdate, reqfilmSign).then(res => {

          movielist = res.data.data;
          console.log(movielist)
          for (let i = 0; i < movielist.length; i++) {
            if (movielist[i].FilmCode == filmCode) {
              that.setData({ isSelected: i })
              isSelected = i;
            
            }
            if (('' + movielist[i].UserScore).length > 1 && typeof (movielist[i].UserScore)!=undefined){
          
                movielist[i].UserScore = movielist[i].UserScore + ".0"
          
             
            }else{
              movielist[i].UserScore ="8.0"
            }
            // if (){
            //   console.log(21342345325324534543)
            // }
          }



          this.setData({ movielist: res.data.data })
        
        }).then(() => {
          return req.GetSignStr(filePlanSgin).then(res => {
            if (res.data.success)
              reqfilePlanSgin = res.data.data;

          }).then(() => {

            return req.GetPlanDateList(strAppCode, cinemapojo.CinemaCode, filmCode, "", "", reqfilePlanSgin).then(res => {
              console.log(res.data.data)
              startdate = res.data.data;
              showdate = [];

              for (let i = 0; i < startdate.length; i++) {
                showdate.push(startdate[i].PlayStartDate.split("T")[0].substr(5, 10))
              }
              console.log(showdate)
              that.setData({ showdate, })
            }).then(() => {
              var plansign = "strAppCode=" + strAppCode + "CinemaCode=" + cinemapojo.CinemaCode + "FilmCode=" + filmCode + "PlayStartDate=" + startdate[0].PlayStartDate + "PlayEndDate=" + startdate[0].PlayStartDate;

              return req.GetSignStr(plansign).then(res => {
                //TODO 获取电影排期签名
                if (res.data.success) {
                  reqplanSgin = res.data.data;
                }
              }).then(() => {
                return req.GetPlanList(strAppCode, cinemapojo.CinemaCode, filmCode, startdate[0].PlayStartDate, startdate[0].PlayStartDate, reqplanSgin).then(res => {
                  // TODO获取档期

                  plandate = res.data.data;
                  var heig = plandate.length * 120 + 'rpx'
                  console.log(plandate)
                  console.log(heig)
                  if (plandate.length <= 0) {
                    that.setData({ iswuchangci: true, plandate: plandate, heig: '600rpx' })
                    wx.hideLoading();
                  } else {
                    for (var i = 0; i < plandate.length; i++) {
                      var time = plandate[i].PlayStartTime.split(":")[0]
                      if (time >= 4 && time < 18) {
                        //白天
                        plandate[i].sun = true;
                      } else {
                        plandate[i].sun = false;
                      }
                    }
                    console.log(plandate)
                    that.setData({ plandate: plandate, iswuchangci: false, heig: heig })
                    wx.hideLoading();
                  }
                })
              })
            })
          })
        })
      })



      //得到日期
      var today = timetool.getNowDay();
      var nextday = timetool.getNextDay();
      var lastday = timetool.getLastDay();


      that.setData({
        today: today,//今天的日期
        nextday: nextday,//明天的日期
        lastday: lastday,//后天的日期
        chkday: today,//默认今天选中
      })


      //结束标识符
      that.setData({
        setWidth: movielist.length * 134 + 'rpx'
      })
    },
    selectedMove: function (e) {
      console.log(e)
      isSelected = e.currentTarget.dataset.id
      this.setData({
        isSelected: isSelected
      })


    },
    /**
      * 滑动事件
      * **/
    scroll: function (e) {
      var that = this;

      var movielist = that.data.movielist;
      var indexnum = that.data.indexnum;
      //向右deltaX>0  向左侧deltaX<0 
      //scrollLeft判断滑动的宽度，获取选中的值
      //向左滑动
      if (e.detail.deltaX < 0) {
        var scrollnum = parseInt(e.detail.scrollLeft / 40);
        indexnum += scrollnum;

        if (indexnum < movielist.length) {
          that.setData({
            chkid: movielist[indexnum].id,
            indexnum: indexnum
          })
        } else {
          that.setData({
            chkid: movielist[movielist.length - 1].id,
            indexnum: movielist.length - 1
          })
        }
      }//向右滑动
      else if (e.detail.deltaX > 0) {
        var scrollnum = parseInt(e.detail.scrollLeft / 40);
        indexnum -= scrollnum;
        if (indexnum < 0) {
          that.setData({
            chkid: movielist[0].id,
            indexnum: 0
          })
        } else {
          that.setData({
            chkid: movielist[indexnum].id,
            indexnum: indexnum
          })
        }
      }
      that.getchkmovie();
    },
    //得到电影
    getchkmovie: function () {
      var that = this;
      var movielist = that.data.movielist;

      var txtarry = [];
      var dyname = "";//电影的名称
      var pingfen = "";//电影的评分
      var shichang = "";//电影的时长
      var chkmovieimg = "";//电影的海报
      //重置数据
      for (var j = 0; j < movielist.length; j++) {
        if (that.data.chkid == movielist[j].id) {
          txtarry[j] = {
            id: movielist[j].id,
            name: movielist[j].name,
            imgpath: movielist[j].imgpath,
            ischk: true,
            pingfen: movielist[j].pingfen,
            shichang: movielist[j].shichang
          }
          dyname = movielist[j].name;//电影的名称
          pingfen = movielist[j].pingfen;//电影的评分
          shichang = movielist[j].shichang;//电影的时长
          chkmovieimg = movielist[j].imgpath;//电影的时长
        } else {
          txtarry[j] = {
            id: movielist[j].id,
            name: movielist[j].name,
            imgpath: movielist[j].imgpath,
            ischk: false,
            pingfen: movielist[j].pingfen,
            shichang: movielist[j].shichang
          }
        }
      }

      that.setData({
        movielist: txtarry,
        dyid: that.data.chkid,//电影id，
        dyname: dyname,//电影的名称
        pingfen: pingfen,//电影的评分
        shichang: shichang,//电影的时长
        chkmovieimg: chkmovieimg,//电影的海报
      })


      //重置数据
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      isSelected = 0;
      idx = 0;
      var pmwidth = "";
      var pixelRatio = "";
      var that = this;
  
      wx.getSystemInfo({
        success: function(res) {
          pmwidth = res.screenWidth;
          pixelRatio = res.pixelRatio;
        
          that.setData({ pmwidth: (pmwidth / 2) - (pmwidth /5/2)})
        },
      })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },


    // 滑动切换tab 
    bindChange: function (e) {
      wx.showLoading({
        title: '加载排期中',
        mask: true
      })
      var that = this;
      that.setData({ currentTab: e.detail.current });
      this.setData({ current: e.detail.current })
      //TODO重新请求日子
      idx = e.detail.current
      var plansign = "strAppCode=" + strAppCode + "CinemaCode=" + cinemapojo.CinemaCode + "FilmCode=" + filmCode + "PlayStartDate=" + startdate[idx].PlayStartDate + "PlayEndDate=" + startdate[idx].PlayStartDate;

      return req.GetSignStr(plansign).then(res => {
        //TODO 获取电影排期签名
        if (res.data.success) {
          reqplanSgin = res.data.data;
        }

      }).then(() => {
        return req.GetPlanList(strAppCode, cinemapojo.CinemaCode, filmCode, startdate[idx].PlayStartDate, startdate[idx].PlayStartDate, reqplanSgin).then(res => {
          // TODO获取档期
          wx.hideLoading();
          plandate = res.data.data;
          console.log(plandate)

          var heig = plandate.length * 120 + 'rpx'
          console.log(heig)

          if (plandate.length <= 0) {
            that.setData({ iswuchangci:true,plandate: plandate, heig: '600rpx' })
            wx.hideLoading();
          } else {
            for (var i = 0; i < plandate.length; i++) {
              var time = plandate[i].PlayStartTime.split(":")[0]
              if (time >= 4 && time < 18) {
                //白天
                plandate[i].sun = true;
              } else {
                plandate[i].sun = false;
              }
            }
            console.log(plandate)
            that.setData({ plandate: plandate, iswuchangci: false, heig: heig, })
            
            setTimeout(function () {
              // 放在最后--
              wx.hideLoading();
            }
              , 1000)
          }

        })
      })
    },
    // 点击tab切换 
    swichNav: function (e) {
      this.setData({ current: e.currentTarget.dataset.current })
      //TODO 获取日期 发送请求


    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    //得到场次的数据
    getchangcilist: function () {
      var that = this;
      //参数部分
      var dyid = that.data.dyid;
      var yyid = that.data.yyid;
      var riqi = that.data.chkday;
      //结束标识符
    },
    //结束标识符

    changeMovie: function (e) {

      var that = this;

      this.setData({
        isSelected: e.detail.current,
        current: 0
      })
      filmCode = movielist[e.detail.current].FilmCode;
      // TODO 请求档期

      /**
       * strAppCode: strAppCode,
        CinemaCode: CinemaCode,
        FilmCode: FilmCode,
        PlayStartDate: PlayStartDate,
        PlayEndDate: PlayEndDate,
        sign: sign
    
        // reqfilePlanSgin
       * */

      filePlanSgin = "strAppCode=" + strAppCode + "CinemaCode=" + cinemapojo.CinemaCode + "FilmCode=" + filmCode + "PlayStartDate=" + "PlayEndDate=";
      return req.GetSignStr(filePlanSgin).then(res => {
        if (res.data.success) {
          reqfilePlanSgin = res.data.data;

        }
      }).then(() => {
        //TODO切换电影
        return req.GetPlanDateList(strAppCode, cinemapojo.CinemaCode, filmCode, "", "", reqfilePlanSgin).then(res => {
          console.log(res.data.data)
          startdate = res.data.data;
          showdate = [];
          for (let i = 0; i < startdate.length; i++) {
            showdate.push(startdate[i].PlayStartDate.split("T")[0].substr(5, 10))
          }

          that.setData({ showdate, })
        }).then(() => {

          var plansign = "strAppCode=" + strAppCode + "CinemaCode=" + cinemapojo.CinemaCode + "FilmCode=" + filmCode + "PlayStartDate=" + startdate[0].PlayStartDate + "PlayEndDate=" + startdate[0].PlayStartDate;

          return req.GetSignStr(plansign).then(res => {
            //TODO 获取电影排期签名
            if (res.data.success) {
              reqplanSgin = res.data.data;
            }

          }).then(() => {
            return req.GetPlanList(strAppCode, cinemapojo.CinemaCode, filmCode, startdate[0].PlayStartDate, startdate[0].PlayStartDate, reqplanSgin).then(res => {
              // TODO获取档期
              plandate = res.data.data;
              console.log(plandate)

              var heig = plandate.length * 120 + 'rpx'
              console.log(heig)

              if (plandate.length <= 0) {
                console.log('武')
                that.setData({ iswuchangci: true, heig: '600rpx', plandate: plandate })
                wx.hideLoading();
              } else {
                for (var i = 0; i < plandate.length; i++) {
                  var time = plandate[i].PlayStartTime.split(":")[0]
                  if (time >= 4 && time < 18) {
                    //白天
                    plandate[i].sun = true;
                  } else {
                    plandate[i].sun = false;
                  }
                }
                that.setData({ plandate: plandate, iswuchangci: false, heig: heig })
              }
            })
          })
        })
      })
    }

  })